package com.fzy.modules.goods.web;

import com.fzy.core.common.ApiController;
import com.fzy.core.common.ResponseData;
import com.fzy.modules.goods.entity.GoodsCategory;
import com.fzy.modules.goods.service.GoodsCategoryService;
import com.fzy.modules.goods.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *商品分类Controller
 */
@RestController
@RequestMapping(value = "/api/goods/category")
public class GoodsCategoryController extends ApiController{
    @Autowired
    private GoodsCategoryService categoryService;
    @Autowired
    private GoodsService goodsService;

    @GetMapping(value = "")
    public ResponseEntity<ResponseData> list(){
        //树形结构查询
        return new ResponseEntity<>(success(categoryService.findAllList()), HttpStatus.OK);
    }
    @GetMapping(value = "/findAll")
    public List<GoodsCategory> findAll(){
        return categoryService.findAll();
    }
    @PostMapping(value = "")
    public ResponseEntity<ResponseData> save(GoodsCategory category){
        if(StringUtils.isNotEmpty(category.getId())){
            return new ResponseEntity<>(success(categoryService.update(category)),HttpStatus.OK);
        }

        return new ResponseEntity<>(success(categoryService.save(category)),HttpStatus.OK);
    }
    @DeleteMapping(value = "/{id}")
    public ResponseEntity<ResponseData> delete(@PathVariable String id) {
        if(categoryService.isChildrenCategory(id)>0){
            return new ResponseEntity<>(fail("该分类有子级分类，不能删除。"),HttpStatus.BAD_GATEWAY);
        }
        if(goodsService.isWithGoodsUnderCategory(id)>0){
            return new ResponseEntity<>(fail("有产品属于该分类，不能删除。"),HttpStatus.BAD_GATEWAY);
        }
        return new ResponseEntity<>(success(categoryService.delete(id)), HttpStatus.OK);
    }

}
